

export type StorageChange = Dict

export type StorageChangeFunc = (e: StorageChange) => void;

function localStorageFocus(str = sessionStorage) {
  const listeners: Set<StorageChangeFunc> = new Set();

  let localState: Storage = str;

  function set(key: string, value: string) {
    localState.setItem(key, value);
  }

  function get(key: string): string | null {
    return localState.getItem(key);
  }

  function deleteItem(key: string) {
    localState.deleteItem(key);
  }

  function clear() {
    localState.clear();
  }

  let prev = null;

  function request(nextStorage: Storage) {
    prev = localState;
    localState = nextStorage;
  }

  function relase() {
    localState = prev;
    prev = null;
  }



  function subscribe(listen: StorageChangeFunc) {
    listeners.add(listen);


    function un() {
      listeners.delete(listen);
    }
    return un;
  }

  function getLocalStorage() {
    return localState;
  }

  return {
    subscribe,
    getLocalStorage,
    set, get, deleteItem, clear, request, relase
  };
}

/**
 * sessionStorage 的存储
 */
export const session = localStorageFocus();

/**
 * localStorageFocus 的存储
 */
export const local = localStorageFocus(localStorage);

